module Jekyll
  class QiniuImage < Liquid::Tag
    def initialize(tag_name, markup, tokens)
      @markup     = markup
      super
    end

    def render(context)
      # Render any liquid variables in tag arguments and unescape template code
      render_markup = Liquid::Template.parse(@markup).render(context).gsub(/\\\{\\\{|\\\{\\%/, '\{\{' => '{{', '\{\%' => '{%')

      markup = /^(?<image_src>[^\s]+\.[a-zA-Z0-9]{3,4})\s*(?<html_attr>[\s\S]+)?$/.match(render_markup)
      raise "Image Tag: can't read this tag. Try {% qimage path/to/img.jpg [attr=\"value\"] %}." unless markup

      image_path = markup[:image_src]
      puts "image_src is #{image_path}"

      # TODO: nowrap?
      qimage_config = context.registers[:site].config.fetch('qimage', {})
      bucket = qimage_config.fetch('bucket', 'images-hikerpig')
      src = "http://#{bucket}.qiniudn.com/#{image_path}"
      "<div class='image-wrap'><img src='#{src}' /></div>"
    end
  end
end

Liquid::Template.register_tag('qimage', Jekyll::QiniuImage)
